<script lang="ts" setup>
  import { uploadFiles } from '@/services/api/file/file';
  import { isArray } from '@/utils/is';
  import { onMounted, reactive, watch } from 'vue';
  // const UploadUrl = import.meta.env.VITE_PROXY_UPLOAD_URL
  const UploadUrl = 'http://139.198.117.15:3000';
  const emits = defineEmits(['onUploadChange']);
  const props = defineProps({
    limit: {
      type: Number,
      default: 9,
    },
    value: {
      type: Array<string>,
      default: () => [],
    },
    fieldName: {
      type: String,
      default: 'file',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  });
  let datas = reactive({
    fileLists: [] as string[],
  });

  onMounted(() => {
    datas.fileLists = props?.value || [];
  });

  watch(
    () => {
      return props.value;
    },
    (n: any) => {
      isArray(n) ? (datas.fileLists = n) : '';
    },
  );

  const afterRead = async (e: any) => {
    let lists: Array<FileModel> = [].concat(e.file);
    lists.map(async (item) => {
      const result = await uploadFilesPromise(item);
      datas.fileLists.push(...result.data);
      emits('onUploadChange', datas.fileLists);
    });
  };

  const deletePic = (event: any) => {
    datas.fileLists.splice(event.index, 1);
    emits('onUploadChange', datas.fileLists);
  };

  const uploadFilesPromise = (item: FileModel) => {
    return new Promise<any>((resolve, reject) => {
      uni.uploadFile({
        url: UploadUrl + '/common/upload/files',
        filePath: item.url,
        name: props.fieldName,
        formData: {},
        success(e) {
          resolve(JSON.parse(e.data));
        },
        fail(err) {
          reject(JSON.parse(err as any));
        },
      });
    });
  };
</script>

<template>
  <u-upload
    :fileList="datas.fileLists"
    :previewFullImage="true"
    :disabled="props.disabled"
    :deletable="!props.disabled"
    @afterRead="afterRead"
    @delete="deletePic"
    :name="props.fieldName"
    multiple
    :maxCount="props.limit"
  ></u-upload>
</template>
<style lang="scss" scoped></style>
